import { h, ref } from 'vue';

import { message, Modal } from 'ant-design-vue';
import { defineStore } from 'pinia';

import {
  bind1688SkuSourceApi,
  bind1688SourceApi,
  deleteBind1688SourceApi,
  get1688SkuListApi,
  getBind1688SourceApi,
} from '#/api';
import { formatMoney, similarity } from '#/utils';

import Bindusehuoyuan from './bindusehuoyuan.vue';
import { formatUpSkuData } from './formatupskudata';
// import { auto1688Store } from './modules';

export const link1688stor = defineStore('link1688', () => {
  const infoitemskuitem = {
    offerId: null,
    code: '',
    specPic: '',
    skuValue: '',
    skuValueList: [],
    buyNum: 1,
    stockNum: 0,
    priceStr: '',
    xiangshidu: 0,
  };
  const getList = ref<any>(() => {});
  const deteail = ref<any>({});
  const getdeteailLoading = ref(false);
  const showLinkSkuStatus = ref(false);
  const bindSkuList = ref<any>([]);
  const bindGoodsList = ref<any>([]);
  const get1688SkuLoding = ref(false);
  const select1688skuitem = ref<any>([]);
  // const isSelectSkuTitle = ref('');
  const isNowSelectItem = ref<any>({});
  const selectItemContent = ref<any>({ ...infoitemskuitem });

  const showIsLinkBindStatus = ref(false);

  const useAutoOfferId = ref<any>(null);

  let skulistdatas: any = {};

  function $reset() {
    // console.log('重置');
    deteail.value = {};
    bindSkuList.value = [];
    bindGoodsList.value = [];
    showLinkSkuStatus.value = false;
    getdeteailLoading.value = false;
    get1688SkuLoding.value = false;
    select1688skuitem.value = [];
    // isSelectSkuTitle.value = '';
    isNowSelectItem.value = {};
    selectItemContent.value = { ...infoitemskuitem };
    skulistdatas = {};
  }

  function pushItem1688SkuItemFu(item: any) {
    item.bindSkuList.push({ ...infoitemskuitem });
  }
  function getBind1688SourceApiFun(productId?: string) {
    getdeteailLoading.value = true;
    getBind1688SourceApi({
      productId: productId || deteail.value.productId,
    })
      .then((_res) => {
        const reloadDatas = _res.bindSkuList.map((item: any, index: number) => {
          item.bindSkuList.forEach((itemr: any) => {
            itemr.skuValue =
              itemr.subList?.map((itemr: any) => itemr.valueName)?.join(';') ||
              '';
          });
          if (!item.bindSkuList || item.bindSkuList.length === 0) {
            pushItem1688SkuItemFu(item);
          }
          return {
            ...item,
            skuValue:
              item.goodsSku?.subList
                ?.map((itemr: any) => itemr.valueName)
                ?.join(';') || '',
            price: `¥${formatMoney(item.goodsSku?.price || 0)}`,

            index: index + 1,
          };
        });
        bindSkuList.value = reloadDatas;
        bindGoodsList.value = _res.bindGoodsList.map(
          (item: any, index: number) => {
            return {
              ...item,
              // price: `¥${formatMoney(item.goodsSku?.price || 0)}`,
              index: index + 1,
            };
          },
        );
      })
      .finally(() => {
        getdeteailLoading.value = false;
      });
  }

  function getDeteail(data: any) {
    $reset();
    deteail.value = data;
    getBind1688SourceApiFun(data.productId);
  }

  async function bind1688SourceApiFun(data: any) {
    getdeteailLoading.value = true;
    if (!data.offerIds || data.offerIds.length === 0) {
      Modal.error({
        title: '提示',
        content: '请先选择货源',
      });
      return (getdeteailLoading.value = false);
    }
    data.productId = deteail.value.productId;
    data.shopId = deteail.value.shopId;
    const res = await bind1688SourceApi(data).finally(() => {
      getdeteailLoading.value = false;
    });
    return res;
  }
  async function getItemInSkuList(item: any, isGetData?: boolean) {
    if (!item.offerId) {
      Modal.error({
        title: '提示',
        content: '请先选择货源',
      });
      return;
    }
    isNowSelectItem.value = item;
    !isGetData && (showLinkSkuStatus.value = true);

    if (skulistdatas[item.offerId]) {
      select1688skuitem.value = skulistdatas[item.offerId];
      return;
    }
    // console.log('item123456789', item);
    get1688SkuLoding.value = true;
    const res = await get1688SkuListApi({
      offerIds: [item.offerId],
    }).finally(() => {
      // showLinkSkuStatus.value = false;
      get1688SkuLoding.value = false;
    });
    const getNowItem = res.find((items: any) => items.offerId === item.offerId);
    getNowItem?.specInfo?.specValues?.forEach((itemr: any) => {
      itemr.isselectid = '';
    });
    select1688skuitem.value = getNowItem;
    skulistdatas[item.offerId] = getNowItem;
    // console.log('res', res);
  }
  function dlt1688bindItem(item: any) {
    Modal.confirm({
      title: '提示',
      content: `确定移除绑定商品【${item.goodsName}】？移除后将会影响订单的自动采购下单。`,
      onOk(clear) {
        clear && clear();
        item.deleteLodin = true;
        const res: any = deleteBind1688SourceApi({
          tbIds: [item.tbId],
        }).finally(() => {
          item.deleteLodin = false;
        });
        if (res) {
          bindGoodsList.value = bindGoodsList.value.filter(
            (itemr: any) => itemr.tbId !== item.tbId,
          );
          getList.value();
        }
      },
    });
    // item.bindSkuList.splice(item.bindSkuList.indexOf(item), 1);
  }

  function selectSkuItemChenge(item: any, itemr: any) {
    item.isselectid = itemr.specId;
    // isSelectSkuTitle.value = '';
    const nowGtValue: any = [];
    // for(let key in selectItemContent.value) {
    //   selectItemContent.value[key] = isNowSelectItem.value[key]
    // }
    selectItemContent.value.offerId = isNowSelectItem.value.offerId;
    selectItemContent.value.buyNum = isNowSelectItem.value.buyNum;
    selectItemContent.value.skuValue = '';
    let specPicImg = '';
    select1688skuitem.value.specInfo.specValues.forEach((itemrr: any) => {
      // itemrr.isselectid = '';
      if (itemrr.isselectid) {
        const getSelectItem = itemrr.values.find(
          (itemrrr: any) => itemrrr.specId === itemrr.isselectid,
        );
        if (getSelectItem) {
          nowGtValue.push(getSelectItem.valueName);
          if (getSelectItem.skuImageUrl) {
            specPicImg = getSelectItem.skuImageUrl;
          }
        }
      }
    });
    const getSkuItems = select1688skuitem.value.specPricesV2.find(
      (iytr: any) => {
        const itemconter = iytr.sellProperties
          .map((itemrrr: any) => itemrrr.valueName)
          .join(';');
        return itemconter === nowGtValue.join(';');
      },
    );
    // console.log('getSkuItems', getSkuItems);
    if (getSkuItems) {
      selectItemContent.value.skuValueList = { ...getSkuItems };
    }
    selectItemContent.value.code = getSkuItems?.code;
    selectItemContent.value.stockNum = getSkuItems?.stockNum;
    selectItemContent.value.priceStr = formatMoney(
      getSkuItems?.supplyPrice || 0,
    );
    selectItemContent.value.skuValue = nowGtValue.join(';');
    selectItemContent.value.specPic = specPicImg;
  }
  function selectendfn() {
    try {
      select1688skuitem.value.specInfo.specValues.forEach((itemrr: any) => {
        if (!itemrr.isselectid) {
          throw new Error(`请选择: ${itemrr.propertyName}`);
        }
      });
      showLinkSkuStatus.value = false;
      for (const key in isNowSelectItem.value) {
        isNowSelectItem.value[key] = selectItemContent.value[key];
      }
      setnums();
    } catch (error) {
      if (error instanceof Error) {
        Modal.error({
          title: '提示',
          content: error.message,
        });
      }
    }
  }
  function setnums() {
    const pushNnters: any = {};
    // console.log('bindSkuList123456789', pushNnters, bindSkuList.value);

    bindSkuList.value.forEach((item: any) => {
      item.bindSkuList.forEach((itemr: any) => {
        // console.log('itemr', itemr);
        if (itemr.offerId) {
          pushNnters[itemr.offerId]
            ? pushNnters[itemr.offerId].push(itemr.skuValue)
            : (pushNnters[itemr.offerId] = [itemr.skuValue]);
        }
        // itemr.offerId &&
        //   (pushNnters[itemr.offerId] = pushNnters[itemr.offerId]
        //     ? pushNnters[itemr.offerId] + 1
        //     : 1);
      });
      bindGoodsList.value.forEach((itemr: any) => {
        if (pushNnters[itemr.offerId] && pushNnters[itemr.offerId].length > 0) {
          const setdata = [...new Set(pushNnters[itemr.offerId])].filter(
            Boolean,
          );
          itemr.skuMatchCount = setdata.length || 0;
          itemr.skuTotal = skulistdatas[itemr.offerId].specPricesV2.length;
        } else {
          itemr.skuMatchCount = 0;
          itemr.skuTotal = skulistdatas[itemr.offerId]
            ? skulistdatas[itemr.offerId].specPricesV2.length
            : 0;
        }
      });
    });
  }
  function clearBindLogs() {
    Modal.confirm({
      title: '提示',
      content: '确定要清空已关联规格吗？',
      onOk: async () => {
        // eslint-disable-next-line unicorn/prefer-structured-clone
        const copyBindSkuList = JSON.parse(JSON.stringify(bindSkuList.value));
        bindSkuList.value = copyBindSkuList.map((item: any) => {
          item.bindSkuList = [{ ...infoitemskuitem }];
          return item;
        });
        setnums();
      },
    });
  }
  function autobindsku() {
    // console.log('当前选择的商品以及sku', bindGoodsList.value);
    // console.log('当前选择的货源⚽️', bindSkuList.value);
    // console.log('相识度匹配', isNowSelectItem.value);
    if (bindGoodsList.value.length === 0) {
      return message.error('请先关联商品');
    }
    Modal.confirm({
      title: '选择关联的货源',
      content: h(Bindusehuoyuan, {}),
      width: 470,
      onOk: async () => {
        if (!useAutoOfferId.value) {
          Modal.error({
            title: '提示',
            content: '请选择关联的货源',
          });
          throw new Error('请选择关联的货源');
        }
        await autoContenter();
      },
    });
  }
  async function autoContenter() {
    const nowUseItem = bindGoodsList.value.find(
      (item: any) => item.offerId === useAutoOfferId.value,
    );
    await getItemInSkuList(nowUseItem, true);
    // console.log(
    //   'nowUseItem',
    //   select1688skuitem.value.specPricesV2,
    //   bindSkuList.value,
    // );
    if (select1688skuitem.value.specPricesV2.length === 0) {
      return Modal.error({
        title: '提示',
        content: '该货源商品没有规格',
      });
    }
    // console.log('select1688skuitem.value', select1688skuitem.value);
    const copyInfoter = [...select1688skuitem.value.specPricesV2];
    const specValues = select1688skuitem.value.specInfo.specValues;
    const copyBindSkuList = [...bindSkuList.value];
    let addNums = 0;
    copyBindSkuList.forEach((item: any) => {
      const shopSkuStr = item.skuValue;
      // 获取相似度 大于30以上

      const getMaxXiangshi = copyInfoter
        .map((itemr: any) => {
          const get1688SkuStr = itemr.sellProperties
            .map((itemrr: any) => itemrr.valueName)
            .join(';');
          const strXiangshi = similarity(shopSkuStr, get1688SkuStr);
          // console.log('相似度', strXiangshi, shopSkuStr, get1688SkuStr);
          itemr.xiangshidu = strXiangshi;
          itemr.skuValue = get1688SkuStr;
          return itemr;
        })
        .sort((a: any, b: any) => b.xiangshidu - a.xiangshidu)[0];
      if (getMaxXiangshi.xiangshidu > 0.3) {
        const getItemImage = specValues[0].values.find((itemerss: any) => {
          return (
            itemerss.valueName === getMaxXiangshi.sellProperties[0].valueName
          );
        })?.skuImageUrl;
        // console.log('getItemImage', getItemImage);
        item.bindSkuList = [
          {
            buyNum: 1,
            code: getMaxXiangshi.code,
            offerId: useAutoOfferId.value,
            priceStr: formatMoney(getMaxXiangshi?.supplyPrice || 0),
            skuValue: getMaxXiangshi.skuValue,
            specPic: getItemImage,
            skuValueList: [getMaxXiangshi],
            stockNum: getMaxXiangshi.stockNum,
            xiangshidu: getMaxXiangshi.xiangshidu,
          },
        ];
        addNums++;
      }
    });
    if (!addNums) {
      return Modal.error({
        title: '提示',
        content: '相似度太低，无法关联',
      });
    }
    bindSkuList.value = copyBindSkuList;
    setnums();
  }

  function saveBind1688Fn() {
    if (bindGoodsList.value.length === 0) {
      return Modal.error({
        title: '提示',
        content: '请选择先关联货源',
      });
    }
    getdeteailLoading.value = true;
    const updata = formatUpSkuData(bindSkuList.value);
    const updataobj = {
      records: JSON.stringify(updata),
      productId: deteail.value.productId,
      bindGoodsList: JSON.stringify(bindGoodsList.value),
    };
    bind1688SkuSourceApi(updataobj)
      .then((_res: any) => {
        getList.value();
        getdeteailLoading.value = false;
        message.success('关联成功');
        showIsLinkBindStatus.value = false;
      })
      .finally(() => {
        getdeteailLoading.value = false;
      });
  }

  return {
    $reset,
    deteail,
    getdeteailLoading,
    getDeteail,
    showLinkSkuStatus,
    bind1688SourceApiFun,
    getBind1688SourceApiFun,
    bindSkuList,
    bindGoodsList,
    getItemInSkuList,
    get1688SkuLoding,
    select1688skuitem,
    pushItem1688SkuItemFu,
    dlt1688bindItem,
    selectSkuItemChenge,
    // isSelectSkuTitle,
    selectendfn,
    selectItemContent,
    infoitemskuitem,
    clearBindLogs,
    autobindsku,
    saveBind1688Fn,
    setnums,
    getList,
    showIsLinkBindStatus,
    useAutoOfferId,
    // bind1688SourceListApiFn,
  };
});
